package com.kaigejava.juc.toolsdemo.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author kaigejava
 * semaphore演示功能的入口
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        //获取餐桌数量
        int tableSize = Restaurant.tableSize;
        Restaurant restaurant = new Restaurant();
        Semaphore semaphore = new Semaphore(tableSize,true);
        for(int i = 1;i<=8;i++){
            final int tableNo = i;
            new Thread(()->{
                //获取资源
                try {
                    TimeUnit.SECONDS.sleep(1);
                    semaphore.acquire();
                    restaurant.setTable(tableNo);
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                    restaurant.releaseTable(tableNo);
                }
            }).start();
        }
    }
}
